import codecs
import os


def append_to_list(list_file_path, text):
    write_list(list_file_path, text, mode="a", dedupe=False)


def append_with_subsidiary(list_file_path, text, subsidiary, mode="a+"):
    with codecs.open(list_file_path, mode=mode, encoding='utf-8') as f:  # 完成一个写一个
        f.write(text + " -> " + subsidiary + "\n")


def write_list(list_file_path, test_list, mode="w", dedupe=True):
    if dedupe:
        test_list = list(set(test_list))
    with codecs.open(list_file_path, mode=mode, encoding='utf-8') as f:
        f.writelines([text + "\n" for text in test_list])

def read_map(list_file_path):
    text_map = {}
    if os.path.isfile(list_file_path):
        with codecs.open(list_file_path, mode='r', encoding='utf-8') as f:
            text_list = f.readlines()
        text_list = list(filter(lambda x: not x.startswith("#"), text_list))  # 先fitler掉#开头的行注释
        for text_item in text_list:
            text_map[text_item.split(" -> ")[0].strip()] = text_item.split(" -> ")[1].strip()
    return text_map

def read_list(list_file_path, dedupe=True):
    if os.path.isfile(list_file_path):
        with codecs.open(list_file_path, mode='r', encoding='utf-8') as f:
            text_list = f.readlines()
        text_list = list(filter(lambda x: not x.startswith("#"), text_list))  # 先fitler掉#开头的行注释
        text_list = [item.split(" -> ")[0].strip() for item in text_list]  # 这个是保留单纯text的text_list
    else:
        text_list = []
    if dedupe:
        text_list = list(set(text_list))
        print(f"dedupe text list from: {list_file_path}, {len(text_list)} -> {len(text_list)} ")  # dedupe
    return text_list